package com.koron.bean.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.koron.bean.system.staff.Constant;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JWTUtils
 * @description
 * @Author zhouj
 * @Date 2021/7/14 19:59
 */
@Slf4j
public class JWTUtils {

    //秘钥 盐
    private static final String SECRET = "SmyC47re$ML%F72x6koqyUQ0XLQOasdsad";

    /**
     * 生成token header.payload.sing
     *
     * @param map
     * @param expired
     * @return
     */
    public static String getToken(Map<String, String> map, Integer expired) {
        Calendar instance = Calendar.getInstance();
        //设置过期时间单位:秒
        instance.add(Calendar.SECOND, expired);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach(builder::withClaim);
        //制定令牌过期时间
        String token = builder.withExpiresAt(instance.getTime())
                //sign
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 验证token 合法性 || 获取token信息方法
     *
     * @param token
     */
    public static DecodedJWT verify(String token) {

        try {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        } catch (TokenExpiredException e) {
            log.warn("invalid token :{}", token);
            log.warn(e.getMessage());
        } catch (Exception e) {
            log.error("invalid token :{}",token);
            log.error(e.getMessage(), e);
        }
        return null;
    }


    public static Map<String,String> payload(String token) {
        Map<String, String> result = new HashMap<>();
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            String account = decodedJWT.getClaim("account").asString();
            String userName = decodedJWT.getClaim("user_name").asString();
            result.put(Constant.ACCOUNT, account);
            result.put(Constant.USERNAME, userName);
            return result;
        } catch (TokenExpiredException e) {
            log.warn("invalid token :{}", token);
            log.warn(e.getMessage());
        } catch (Exception e) {
            log.error("invalid token :{}",token);
            log.error(e.getMessage(), e);
        }
        return null;
    }
}

